var pageSize = 20;
var startIndex = 0;
var isLoadUpInfo = false;

var searchDs;
var vtypeDs;
var searchKeyWordField;
var vTypeCombo;
var main_Panel;

function getSearchForm() {
	var sdRadio = new Ext.form.Radio({
		id : 'sd',
		boxLabel : '标清',
		name : 'infoFormat',
		value : '0',
		checked : true
	})

	var hdRadio = new Ext.form.Radio({
		id : 'hd',
		boxLabel : '高清',
		name : 'infoFormat',
		value : '1',
		checked : false
	})

	vtypeDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.JsonReader({
			root : 'p_types',
			fields : [ {
				name : 'name'
			}, {
				name : 'code'
			} ]
		})
	});
	vtypeDs.baseParams = {
		'cmd' : 'keysubject',
		'action' : 'findPType'
	};

	vTypeCombo = new Ext.form.MultiComboBox({
		id : 'vTypeCombo',
		editable : false,
		name : 'vTypeCombo',
		displayField : "name",
		labelSeparator : '',
		labelWidth : 80,
		labelAlign : 'right',
		valueField : 'code',
		displaySeparator : ' ',
		valueSeparator : ' ',
		hiddenName : 'hiddenNameId',
		fieldLabel : TXT_vod_category_title,
		mode : 'local',
		store : vtypeDs,
		triggerAction : 'all',
		width : 190,
		emptyText : TXT_vod_category_empty_msg,
		listeners : {
			'change' : vTypeChangeListener
		}
	});

	vtypeDs.load({
		// TODO temp disable offline for '节目单'.
		callback : function(r, options, success) {
			var i;
			for (i = 0; i < r.length; i++) {
				if (r[i].get('name') == '节目单') {
					break;
				}
			}
			if (i !== r.length)
				vtypeDs.remove(r[i]);
		}
	});

	searchKeyWordField = new Ext.form.TextField(
			{
				fieldLabel : '<b style="color:red;">* </b> '
						+ TXT_search_keyword_label,
				id : 'keyword',
				name : 'keyword',
				allowBlank : false,
				afterRender : function() {
					searchKeyWordField.getEl().on('keyup', function(e) {
						e.stopEvent();
						if ((e.getKey() == Ext.EventObject.ENTER)) {
							searchButtonClick();
						}
					})
				}
			});

	var searchButton = new Ext.Button({
		id : "searchButton",
		text : TXT_search_button_text,
		type : "button",
		cls : 'x-toolbar',
		handler : searchButtonClick
	});

	var selectAllBtn = new Ext.Button({
		id : "selectAllBtn",
		text : TXT_vod_select_all,
		type : "button",
		cls : 'x-toolbar',
		handler : selectAll
	});

	var unselectAllBtn = new Ext.Button({
		id : "unselectAllBtn",
		text : TXT_vod_unselect_all,
		type : "button",
		cls : 'x-toolbar',
		handler : unselectAll
	});

	var offLineBtn = new Ext.Button({
		id : "offLineBtn",
		text : TXT_vod_off_line,
		type : "button",
		cls : 'x-toolbar',
		handler : offLineVods
	});

	var upInfoBtn = new Ext.Button({
		id : "upInfoBtn",
		text : TXT_vod_up,
		type : "button",
		cls : 'x-toolbar',
		handler : upAllSelectedInfo
	});

	var cancelUpInfoBtn = new Ext.Button({
		id : "cancelUpInfoBtn",
		text : TXT_vod_cancel_up,
		type : "button",
		cls : 'x-toolbar',
		handler : cancelUpAllSelectedInfo
	});

	var allUpInfoBtn = new Ext.Button({
		id : "allUpInfoBtn",
		text : TXT_vod_all_up_info,
		type : "button",
		cls : 'x-toolbar',
		handler : allUpInfo
	});

	var searchForm = new Ext.FormPanel({
		frame : true,
		layout : 'column',
		labelAlign : 'right',
		buttonAlign : 'left',
		labelWidth : 60,
		border : false,
		region : 'north',
		height : 60,
		tbar : [
				"-",
				"<span style='font-weight:bold;font-size:11px'>"
						+ TXT_vod_manager + "</span>", '->' ],
		style : 'text-align:right;',
		items : [ {
			width : 50,
			layout : 'form',
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ selectAllBtn ]
		}, {
			width : 70,
			layout : 'form',
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ unselectAllBtn ]
		}, {
			width : 60,
			layout : 'form',
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ offLineBtn ]
		}, {
			width : 60,
			layout : 'form',
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ upInfoBtn ]
		}, {
			width : 68,
			layout : 'form',
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ cancelUpInfoBtn ]
		}, {
			width : 90,
			layout : 'form',
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ allUpInfoBtn ]
		}, {
			columnWidth : .99,
			html : "&nbsp;"
		}, {
			width : 50,
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ sdRadio ]
		}, {
			width : 50,
			style : 'margin:4px 0 0 0;',
			labelAlign : 'left',
			items : [ hdRadio ]
		}, {
			width : 10,
			html : "&nbsp;"
		}, {
			width : 260,
			layout : 'form',
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ vTypeCombo ]
		}, {
			layout : 'form',
			width : 200,
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ searchKeyWordField ]
		}, {
			layout : 'form',
			width : 50,
			style : 'margin:4px 0 0 0;',
			buttonAlign : 'left',
			items : [ searchButton ]
		} ]
	});

	return searchForm;
}

function getSearchGrid() {
	var searchSm = new Ext.grid.RowSelectionModel({
		singleSelect : true
	});
	var searchCm = new Ext.grid.ColumnModel(
			[
					{
						header : "<div style='text-align:center;width:100%;'>"
								+ TXT_common_select + "</div>",
						dataIndex : 'index',
						width : 80,
						fixed : true,
						renderer : function(v) {
							var rowNumber = v % pageSize;
							return "<div style='text-align:center;'><input type='checkbox' name='vodIndex' value='"
									+ rowNumber + "'></input></div>";
						}
					},
					{
						header : TXT_vod_name,
						dataIndex : 'name',
						width : 290,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : TXT_vod_type,
						dataIndex : 'bizType',
						width : 100,
						fixed : true,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : 'Code',
						dataIndex : 'code',
						width : 230,
						fixed : true,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : TXT_vod_update_for_index_time,
						dataIndex : 'updateTimeForIndex',
						width : 140,
						fixed : true,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '<div style="text-align:center" height="20">'
								+ TXT_Common_Operation + '</div>',
						dataIndex : 'index',
						width : 120,
						fixed : true,
						renderer : function(v) {
							var index = v % pageSize;
							var record = searchDs.getAt(index);
							var up_flag = record.get("up_flag");
							var upFlagText;
							if (up_flag == 0) {
								upFlagText = TXT_vod_up;
							} else {
								upFlagText = TXT_vod_cancel_up;
							}

							return "<div width='100%' style='text-align:center'><a style='color:blue;text-decoration:underline;cursor:pointer' onClick=offLineVod('"
									+ index
									+ "')>"
									+ TXT_vod_off_line
									+ "</a> / <a style='color:blue;text-decoration:underline;cursor:pointer' onClick=updateInfoUpFlag('"
									+ index + "')>" + upFlagText + "</a></div>";
						}
					}
			]);

	searchDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.ExJsonReader({
			root : 'results',
			totalProperty : 'totalCount',
			id : 'id',
			fields : [ {
				name : 'name'
			}, {
				name : 'bizType'
			}, {
				name : 'code'
			}, {
				name : 'updateTimeForIndex'
			}, {
				name : 'infoFlag'
			}, {
				name : 'up_flag'
			}, {
				name : 'id'
			}, {
				name : 'index'
			} ]
		})
	});

	searchDs.baseParams = {
		'cmd' : 'info',
		'action' : 'findInfoFromEngine'
	};

	var searchGrid = new Ext.grid.GridPanel(
			{
				border : false,
				region : 'center',
				ds : searchDs,
				cm : searchCm,
				sm : searchSm,
				stripeRows : true,
				loadMask : {
					msg : 'searching...'
				},
				viewConfig : {
					forceFit : true
				},
				listeners : {
					'keydown' : function(e) {
						e.stopEvent();
						PagingToolbar_KeyEvent(Ext
								.getCmp('searchGridPagingToolbar'), e);
					}
				},
				bbar : new Ext.PagingToolbar(
						{
							id : 'searchGridPagingToolbar',
							pageSize : pageSize,
							height : 18,
							store : searchDs,
							displayInfo : true,
							displayMsg : TXT_common_paging,
							emptyMsg : TXT_common_no,
							onPagingKeydown : function(e) {
								PagingToolbar_KeyEvent(this, e);
							},
							onClick : function(which) {
								switch (which) {
								case 'prev':
									startIndex = startIndex - pageSize;
									break;
								case 'first':
									startIndex = 0;
									break;
								case 'next':
									startIndex = startIndex + pageSize;
									break;
								case 'last':
									startIndex = ((this.store.getTotalCount() / pageSize) | 0)
											* pageSize;
									break;
								default:
								}

								// Gets data
								loadData(isLoadUpInfo);
							}
						})
			});

	return searchGrid;
}

function PagingToolbar_KeyEvent(thisPagingToolbar, e) {
	if ((e.getKey() == Ext.EventObject.ENTER)) {
		var currPage = thisPagingToolbar.readPage();
		var totalPage = thisPagingToolbar.getPageData().pages;

		if (currPage > totalPage) {
			Ext.Msg.alert(TXT_common_hint, TXT_Common_Correct_PageNum);
			return;
		} else {
			if (currPage <= 0) {
				startIndex = 0;
			} else {
				startIndex = (currPage - 1) * pageSize;
			}

			// Gets data
			loadData(isLoadUpInfo);
		}
	}
	return;
}

function displaySearchPanel() {

	var searchForm = getSearchForm();
	var searchGrid = getSearchGrid();
	main_Panel = new Ext.Panel({
		border : false,
		region : 'center',
		layout : 'border',
		margins : '5 5 5 5',
		cmargins : '5 5 5 5',
		items : [ searchForm, searchGrid ]
	});

	BestvSearch.glb_mainPanel.add(main_Panel);
	BestvSearch.drawMainFrame(TXT_app_name + ' - ' + TXT_search_title, null);
}

Ext.onReady(displaySearchPanel);

function searchButtonClick() {
	startIndex = 0;
	isLoadUpInfo = false;
	// Gets data
	loadData(isLoadUpInfo);
}

function vTypeChangeListener() {
	// Gets data
	loadData(isLoadUpInfo);
}

function selectAll() {
	var checkBoxs = document.getElementsByName("vodIndex");
	for ( var i = 0; i < checkBoxs.length; i++) {
		checkBoxs[i].checked = true;
	}
}

function unselectAll() {
	var checkBoxs = document.getElementsByName("vodIndex");
	for ( var i = 0; i < checkBoxs.length; i++) {
		checkBoxs[i].checked = false;
	}
}

function allUpInfo() {
	startIndex = 0;
	isLoadUpInfo = true;
	loadData(isLoadUpInfo);
}

function loadData(loadAllUpInfo) {

	var keyWord = '';
	if(searchKeyWordField && searchKeyWordField.getValue() ){
		keyWord = searchKeyWordField.getValue().trim();
	}

	if (keyWord == "" && !loadAllUpInfo) {
		return;
	}

	var infoTypes = vTypeCombo.getValue();
	if (infoTypes == "") {
		infoTypes = null;
	}

	var isHd = false;
	var infoFormat = document.getElementsByName('infoFormat');
	for ( var i = 0; i < infoFormat.length; i++) {
		if (infoFormat[i].checked) {
			if (infoFormat[i].id == 'hd') {
				isHd = true;
				break;
			}
		}
	}

	var searchCmd = 'searchCategory';
	if (isHd) {
		searchCmd = 'searchAcronymCategory';
	}

	searchDs
			.load({
				params : {
					keyword : keyWord,
					infoType : infoTypes,
					start : startIndex,
					limit : pageSize,
					loadAllUpInfo : loadAllUpInfo,
					searchCmd : searchCmd,
					flag : Math.random()
				},
				callback : function(r, options, success) {
					if (r.length == 0 && !success) {
						if (searchDs.reader.responseText == '[null]') {
							Ext.Msg
									.alert(
											TXT_common_hint,
											TXT_common_relogin,
											function() {
												window.location.href = '../eni/common/logout.jsp';
											});
							return;
						} else {
							Ext.Msg.alert(TXT_common_hint,
									TXT_SITE_CONFIGURATION_CHECK);
							return;
						}
					}
				}
			});
}

function offLineVod(index) {
	var record = searchDs.getAt(index);
	var name = record.get("name");
	var code = record.get("code");
	var bizType = record.get("bizType");

	Ext.Msg
			.confirm(
					TXT_vod_off_line_confirm_Title,
					TXT_vod_off_line_confirm_msg
							+ TXT_vod_name
							+ ":"
							+ name
							+ "<br>"
							+ TXT_vod_type
							+ ": "
							+ bizType
							+ "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Code: "
							+ code, function(btn) {
						if (btn == 'yes') {
							var url = DISPATCH_URL
									+ "?cmd=info&action=offLineVod&code="
									+ code;

							var conn = Ext.lib.Ajax.getConnectionObject().conn;

							conn.open("GET", url, false);
							conn.send(null);
							if (conn.responseText == 'success') {
								Ext.Msg.alert(TXT_common_hint,
										TXT_vod_off_line_success);
							}
						}
					});
}

function updateInfoUpFlag(index) {
	var record = searchDs.getAt(index);
	var name = record.get("name");
	var bizType = record.get("bizType");
	var id = record.get("id");
	var upflag = record.get("up_flag");
	var infoFlag = record.get("infoFlag");

	var confirmTitle = TXT_vod_up_confirm_Title;
	var confirmMsg;
	var successMsg;
	if (upflag == 0) {
		confirmMsg = TXT_vod_up_confirm_msg + TXT_vod_name + ":" + name
				+ "<br>" + TXT_vod_type + ": " + bizType + "<br>";
		successMsg = TXT_vod_up_success;
		upflag = 1;

	} else {
		confirmMsg = TXT_vod_up_cancel_confirm_msg + TXT_vod_name + ":" + name
				+ "<br>" + TXT_vod_type + ": " + bizType + "<br>";
		successMsg = TXT_vod_up_cancle_success;
		upflag = 0;
	}
	var jsonParas = "[{id:" + id + ",up_flag:" + upflag + ",infoFlag:"
			+ infoFlag + "}]";
	var url = DISPATCH_URL + "?cmd=info&action=updateInfoUpFlag&jsonPara="
			+ jsonParas + '&flag=' + Math.random();

	confirmHandle(confirmTitle, confirmMsg, url, successMsg);
}

function upAllSelectedInfo(upflag) {
	updateAllInfoUpFlag(1);
}

function cancelUpAllSelectedInfo(upflag) {
	updateAllInfoUpFlag(0);
}

function updateAllInfoUpFlag(toUpFlag) {
	var checkBoxs = document.getElementsByName("vodIndex");

	var jsonParas = "[";
	for ( var i = 0; i < checkBoxs.length; i++) {
		if (checkBoxs[i].checked) {
			var record = searchDs.getAt(checkBoxs[i].value);
			var id = record.get("id");
			var infoFlag = record.get("infoFlag");
			jsonParas += "{id:" + id + ",up_flag:" + toUpFlag + ",infoFlag:"
					+ infoFlag + "},"
		}
	}

	if (jsonParas == "[") {
		if (toUpFlag == 0) {
			Ext.Msg.alert(TXT_common_hint, TXT_vod_up_cancel_select_msg);
		} else {
			Ext.Msg.alert(TXT_common_hint, TXT_vod_up_select_msg);
		}
		return;
	} else {
		jsonParas = jsonParas.substr(0, jsonParas.length - 1) + "]"
	}

	var confirmTitle = TXT_vod_up_confirm_Title;
	var confirmMsg;
	var successMsg;
	if (toUpFlag == 0) {
		confirmMsg = TXT_vod_up_cancel_mutil_msg;
		successMsg = TXT_vod_up_cancle_success;
	} else {
		confirmMsg = TXT_vod_up_mutil_msg;
		successMsg = TXT_vod_up_success;
	}
	var url = DISPATCH_URL + "?cmd=info&action=updateInfoUpFlag&jsonPara="
			+ jsonParas + '&flag=' + Math.random();

	confirmHandle(confirmTitle, confirmMsg, url, successMsg);
}

function confirmHandle(confirmTitle, confirmMsg, url, successMsg) {
	Ext.Msg.confirm(confirmTitle, confirmMsg, function(btn) {
		if (btn == 'yes') {
			var conn = Ext.lib.Ajax.getConnectionObject().conn;
			conn.open("GET", url, false);
			conn.send(null);
			if (conn.responseText == 'success') {
				Ext.Msg.alert(TXT_common_hint, successMsg);
			} else {
				Ext.Msg.alert(TXT_common_hint, TXT_common_access_fail);
			}
		}
	});
}

function offLineVods() {
	var checkBoxs = document.getElementsByName("vodIndex");
	var vods = "";

	// Gets vods
	for ( var i = 0; i < checkBoxs.length; i++) {
		if (checkBoxs[i].checked) {
			var record = searchDs.getAt(checkBoxs[i].value);
			var code = record.get("code");
			vods = code + "," + vods;
		}
	}

	if (vods == "") {
		Ext.Msg.alert(TXT_common_hint, TXT_vod_off_line_select_msg);
		return;
	}

	Ext.Msg.confirm(TXT_vod_off_line_confirm_Title,
			TXT_mutil_vod_off_line_confirm_msg, function(btn) {
				if (btn == 'yes') {
					var url = DISPATCH_URL
							+ "?cmd=info&action=offLineVod&code="
							+ vods.substring(0, vods.length - 1);

					var conn = Ext.lib.Ajax.getConnectionObject().conn;

					conn.open("GET", url, false);
					conn.send(null);
					if (conn.responseText == 'success') {
						Ext.Msg
								.alert(TXT_common_hint,
										TXT_vod_off_line_success);
					}
				}
			});
}
